package com.nicolasprof.profgallery.effects {
	import gs.TweenLite;

	import com.nicolasprof.profgallery.Engine;

	import flash.display.Bitmap;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.geom.Point;

	/**
	 * @author Nicolas Prof
	 */
	public class BricksEffect extends ParticleEffect {
		public function BricksEffect() {
			super();
		}
		override public function build(...$layers) : void {
			var config: XML = getConfig();
			var countX : int = Math.max(config.@countX, 1);
			var countY : int = Math.max(config.@countY, 1);
			var bitmap : Bitmap = $layers[0];
			var width : Number = bitmap.width;
			var height : Number = bitmap.height;
			var mask : Sprite = $layers[1];
			var regPoint: String = config.@regPoint;
			var brickWidth : int = Math.ceil(width / countX);
			var brickHeight : int = Math.ceil(height / countY);
			
			var i: int, j:int, k:int;
			var offset : Point = getOffset(brickWidth, brickHeight, regPoint);
			var delayFactor: Number;
			var xmlDelay: Number = config.@delay;
			var xmlTime: Number = config.@time;
			var rotation: Number = config.@rotation;
			var len: int = countX * countY;
			var posX: Number;
			var posY: Number;
			var offsetX: Number = config.@moveX;
			var offsetY: Number = config.@moveY;
			
			bitmap.mask = mask;
			parseEase();
			
			for(j =0; j < countY; j++){
				for(i=0; i < countX;i++){
					k++;
					
					var brick : Shape = getBrick(brickWidth, brickHeight, regPoint);
					
					mask.addChild(brick);
					
					brick.x = posX = -offset.x + i * brickWidth;
					brick.y = posY = -offset.y + j * brickHeight;	
					brick.x += offsetX;
					brick.y += offsetY;
					brick.scaleX = brick.scaleY = 0;
					brick.rotation = rotation;
					delayFactor = _ease(k, 0, xmlDelay, len);
					TweenLite.to(brick, xmlTime, {scaleX:1, scaleY:1, x: posX, y : posY, rotation:0, delay: delayFactor, overwrite:0});
				}
			}
		}

		private function getBrick($width: int, $height: int, $reg:String) : Shape {
			var brick : Shape = new Shape();
			var offset : Point = getOffset($width, $height, $reg);
			
			brick.graphics.beginFill(0xFF0000);
			brick.graphics.drawRect(offset.x, offset.y, $width, $height);
			brick.graphics.endFill();
			return brick;
		}
		override protected function getConfig() : XML {
			var config : XML = Engine.CONFIG_XML;
			return config.effects.bricks[0];
		}
	}
}
